{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-05-06T13:52:15.146276Z",
     "start_time": "2025-05-06T13:52:15.124276Z"
    }
   },
   "source": [
    "import random\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch import nn"
   ],
   "outputs": [],
   "execution_count": 6
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T14:05:24.119757Z",
     "start_time": "2025-05-06T14:05:24.097757Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 模型定义\n",
    "class LinearModel(nn.Module):\n",
    "  def __init__(self):\n",
    "    super().__init__()\n",
    "    self.weight = nn.Parameter(torch.randn(1))\n",
    "    self.bias = nn.Parameter(torch.randn(1))\n",
    "  def forward(self, input):\n",
    "    return (input * self.weight) + self.bias"
   ],
   "id": "823943bfba158a61",
   "outputs": [],
   "execution_count": 28
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T14:05:25.549662Z",
     "start_time": "2025-05-06T14:05:25.526654Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 数据\n",
    "w = 2\n",
    "b = 3\n",
    "xlim = [-10, 10]\n",
    "x_train = np.random.randint(low=xlim[0], high=xlim[1], size=30)\n",
    "y_train = [w * x + b + random.randint(0,2) for x in x_train]"
   ],
   "id": "6c183fbd8b1c63f5",
   "outputs": [],
   "execution_count": 29
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-06T14:05:51.362057Z",
     "start_time": "2025-05-06T14:05:51.168029Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from torch.utils.tensorboard import SummaryWriter\n",
    "# 训练\n",
    "model = LinearModel()\n",
    "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
    "# 定义优化器\n",
    "optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, weight_decay=1e-2, momentum=0.9)\n",
    "\n",
    "writer = SummaryWriter()\n",
    "\n",
    "for n_iter in range(500):\n",
    "  input = torch.from_numpy(x_train)\n",
    "  output = model(input)\n",
    "  loss = nn.MSELoss()(output, y_train)\n",
    "  model.zero_grad()\n",
    "  loss.backward()\n",
    "  optimizer.step()\n",
    "  writer.add_scalar('Loss/train', loss, n_iter)\n"
   ],
   "id": "6cd736b8aa2f92a3",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\liyan\\AppData\\Local\\Temp\\ipykernel_35592\\2335710683.py:4: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.detach().clone() or sourceTensor.detach().clone().requires_grad_(True), rather than torch.tensor(sourceTensor).\n",
      "  y_train = torch.tensor(y_train, dtype=torch.float32)\n"
     ]
    },
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<string>, line 1)",
     "output_type": "error",
     "traceback": [
      "Traceback \u001B[1;36m(most recent call last)\u001B[0m:\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3579\u001B[0m in \u001B[0;35mrun_code\u001B[0m\n    exec(code_obj, self.user_global_ns, self.user_ns)\u001B[0m\n",
      "\u001B[0m  Cell \u001B[0;32mIn[32], line 6\u001B[0m\n    optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, weight_decay=1e-2, momentum=0.9)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\optim\\sgd.py:63\u001B[0m in \u001B[0;35m__init__\u001B[0m\n    super().__init__(params, defaults)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\optim\\optimizer.py:369\u001B[0m in \u001B[0;35m__init__\u001B[0m\n    self.add_param_group(cast(dict, param_group))\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_compile.py:46\u001B[0m in \u001B[0;35minner\u001B[0m\n    import torch._dynamo\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\__init__.py:53\u001B[0m\n    from .polyfills import loader as _  # usort: skip # noqa: F401\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\polyfills\\loader.py:25\u001B[0m\n    POLYFILLED_MODULES: tuple[\"ModuleType\", ...] = tuple(\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\polyfills\\loader.py:26\u001B[0m in \u001B[0;35m<genexpr>\u001B[0m\n    importlib.import_module(f\".{submodule}\", package=polyfills.__name__)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\importlib\\__init__.py:126\u001B[0m in \u001B[0;35mimport_module\u001B[0m\n    return _bootstrap._gcd_import(name[level:], package, level)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\polyfills\\builtins.py:31\u001B[0m\n    def all(iterable: Iterable[object], /) -> bool:\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\decorators.py:427\u001B[0m in \u001B[0;35mwrapper\u001B[0m\n    rule_map: dict[Any, type[VariableTracker]] = get_torch_obj_rule_map()\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\trace_rules.py:2870\u001B[0m in \u001B[0;35mget_torch_obj_rule_map\u001B[0m\n    obj = load_object(k)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\trace_rules.py:2901\u001B[0m in \u001B[0;35mload_object\u001B[0m\n    val = _load_obj_from_str(x[0])\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_dynamo\\trace_rules.py:2885\u001B[0m in \u001B[0;35m_load_obj_from_str\u001B[0m\n    return getattr(importlib.import_module(module), obj_name)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\importlib\\__init__.py:126\u001B[0m in \u001B[0;35mimport_module\u001B[0m\n    return _bootstrap._gcd_import(name[level:], package, level)\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_higher_order_ops\\map.py:6\u001B[0m\n    from torch._functorch.aot_autograd import AOTConfig, create_joint\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_functorch\\aot_autograd.py:135\u001B[0m\n    from .partitioners import default_partition\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_functorch\\partitioners.py:37\u001B[0m\n    from ._activation_checkpointing.graph_info_provider import GraphInfoProvider\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\torch\\_functorch\\_activation_checkpointing\\graph_info_provider.py:3\u001B[0m\n    import networkx as nx\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\networkx\\__init__.py:23\u001B[0m\n    config = utils.backends._set_configs_from_environment()\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\networkx\\utils\\backends.py:574\u001B[0m in \u001B[0;35m_set_configs_from_environment\u001B[0m\n    backends=Config(\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\site-packages\\networkx\\utils\\configs.py:84\u001B[0m in \u001B[0;35m__new__\u001B[0m\n    cls = dataclass(\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\dataclasses.py:1175\u001B[0m in \u001B[0;35mwrap\u001B[0m\n    return _process_class(cls, init, repr, eq, order, unsafe_hash,\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\dataclasses.py:1024\u001B[0m in \u001B[0;35m_process_class\u001B[0m\n    _init_fn(all_init_fields,\u001B[0m\n",
      "\u001B[0m  File \u001B[0;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\dataclasses.py:579\u001B[0m in \u001B[0;35m_init_fn\u001B[0m\n    return _create_fn('__init__',\u001B[0m\n",
      "\u001B[1;36m  File \u001B[1;32mE:\\Work\\conda-envs\\envs\\py310\\lib\\dataclasses.py:432\u001B[1;36m in \u001B[1;35m_create_fn\u001B[1;36m\n\u001B[1;33m    exec(txt, globals, ns)\u001B[1;36m\n",
      "\u001B[1;36m  File \u001B[1;32m<string>:1\u001B[1;36m\u001B[0m\n\u001B[1;33m    def __create_fn__(_type_nx-loopback, MISSING, _HAS_DEFAULT_FACTORY, __dataclass_builtins_object__, _return_type):\u001B[0m\n\u001B[1;37m                              ^\u001B[0m\n\u001B[1;31mSyntaxError\u001B[0m\u001B[1;31m:\u001B[0m invalid syntax\n"
     ]
    }
   ],
   "execution_count": 32
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
